package com.wjbgn.bsolver.user.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wjbgn.bsolver.user.entity.UserDO;
import com.wjbgn.bsolver.user.mapper.UserMapper;
import com.wjbgn.bsolver.user.service.UserService;
import com.wjbgn.stater.dto.Result;
import com.wjbgn.stater.util.redis.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

/**
 * Description:
 * Create Date: 2022-03-11T10:11:42.594
 *
 * @author wjbgn
 * @version 1.0
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService {

    @Autowired
    private RedisUtil redisUtil;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result saveUser(UserDO userDO) {
        UserDO username = this.getOne(new QueryWrapper<>(new UserDO(userDO.getUsername())));
        if (ObjectUtil.isNotEmpty(username)) {
            return Result.failed("用户名已存在");
        }
        UserDO user = new UserDO();
        user.setEmail(userDO.getEmail());
        UserDO email = this.getOne(new QueryWrapper<>(user));
        if (!ObjectUtils.isEmpty(email)) {
            return Result.failed("当前邮箱已绑定");
        }
        boolean flag = this.save(userDO);
        if (flag) {
            UserDO one = this.getOne(new QueryWrapper<>(new UserDO(userDO.getUsername())));
            redisUtil.setObject("userInfo:" + userDO.getUsername(), one.getId());
            return Result.success("注册成功");
        }
        return Result.failed("注册失败");
    }
}